package com.tcredit.spider.web.service;

import java.util.concurrent.Future;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class AsyncTestService {

	private final Logger logger = LogManager.getLogger(AsyncTestService.class);

	private final RestTemplate restTemplate;

	public AsyncTestService(RestTemplateBuilder restTemplateBuilder) {
		this.restTemplate = restTemplateBuilder.build();
	}

	/**
	 * 使用了@Async/@Transactional来标注，但是无法产生事务控制的目的.
	 * 使用了@Async来标注，B中调用了C、D，C/D分别使用@Transactional做了标注，则可实现事务控制的目的。
	 */
	@Async
	public Future<String> findUser(String user) throws InterruptedException {
		logger.info("Looking up " + user);
		String results = restTemplate.getForObject("https://www.baidu.com/", String.class);
		// 模拟业务，延迟10秒
		Thread.sleep(10000L);
		return new AsyncResult<>("hello, my name is" + user + " my blog is: " + results);
	}

}